<template>
  <div class="order-warp">
    <div class="search">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        @submit.native.prevent
      >
        <el-form-item label="用户名">
          <el-input
            v-model="queryParams.username"
            clearable
            placeholder="输入用户名"
            @keyup.enter.native="handleQuery"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            v-model="queryParams.type"
            clearable
            placeholder="选择状态"
            @change="handleQuery"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" plain @click="handleQuery"
            >搜索</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="userList" stripe style="width: 100%">
      <el-table-column prop="id" label="用户ID" width="80" />
      <el-table-column prop="username" label="用户名" width="100" />
      <el-table-column prop="name" label="姓名" width="80" />
      <el-table-column label="身份证" width="160">
        <template #default="scope">
         <p v-if="scope.row.idCard != null && scope.row.idCard != '' ">
                    {{scope.row.idCard.replace(/^(.{6})(?:\d+)(.{4})$/, "$1****$2")}}
                  </p>
                  <p v-else>未知</p>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="120" />
      <el-table-column label="用户类型" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.type == 0" type="info"> 普通用户 </el-tag>
          <el-tag v-if="scope.row.type == 1" type="danger"> 管理员 </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否管理员" width="100">
        <template #default="scope">
          <el-switch
            @change="doUpdateType($event,scope.row.id)"
            :disabled="scope.row.id == 1"
            v-model="scope.row.type"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#aaaaaa"
          />
        </template>
      </el-table-column>
      <el-table-column label="存在订单" width="80">
        <template #default="scope">
          {{ scope.row.haveOrder == 1 ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间" width="180" />
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button
            type="text"
            :icon="Edit"
            size="small"
            @click="toResetPassword(scope.row.id)"
            >重置密码</el-button
          >
          <el-popconfirm
            v-if="scope.row.haveOrder == 0 && scope.row.id != 1"
            title="确定删除该用户?"
            @confirm="doDeleteUser(scope.row.id)"
          >
            <template #reference>
              <el-button type="text" :icon="Delete" size="small"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div></div>
    <div class="footer">
      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>


  <el-dialog v-model="dialogVisible" title="重置密码" width="500px">
    <el-form
      :rules="resetRules"
      style="margin-top: 20px"
      ref="formEl"
      label-width="100px"
      :model="{}"
    >
      <el-form-item label="密码" prop="password">
        <el-input
          style="width: 100%"
          placeholder="输入新密码"
          v-model="password"
          :maxlength="20"
          :minlength="6"
        ></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="doResetPassword">确定</el-button>
      </span>
    </template>
  </el-dialog>
  </div>

</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { getUserList, resetPassword, deleteUser,updateType } from "../../api/user";
import { Search, Edit, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

const currentUserId = ref({});

const formEl = ref();

const clearWarning = () => {
  if (formEl.value) {
    formEl.value.resetFields();
  }
};



const dialogVisible = ref(false);

const password = ref(null)



const validatePassword = (rule, value, callback) => {
  if (!password.value) {
    callback(new Error("请输入密码"));
  }else if(password.value.length<6) {
    callback(new Error("密码长度最少6位"));
  } else {
    callback();
  }
};
const resetRules = reactive({
  password: [{ validator: validatePassword, trigger: "blur" }],
});
const toResetPassword = (userId) => {
    password.value = null
  currentUserId.value = userId;
  clearWarning();
  dialogVisible.value = true;
};

const doResetPassword = ()=>{
    formEl.value.validate((valid) => {
    if (valid) {
      resetPassword(currentUserId.value, password.value).then((res) => {
        ElMessage.success("密码重置成功");
        getList();
        dialogVisible.value = false;
      });
    } else {
      console.log("error submit!");
      return false;
    }
  });
}

const doDeleteUser = (id) => {
  deleteUser(id).then((res) => {
    ElMessage.success("删除成功");
    getList();
  });
};

const queryParams = ref({
  username: null,
  type: null,
  current: 1,
  size: 10,
});

const typeList = [
  {
    id: 0,
    name: "普通用户",
  },
  {
    id: 1,
    name: "管理员",
  },
];

const doUpdateType = (type,userId)=>{
    updateType(userId,type)
}



const userList = ref([]);

const total = ref(0);
const getList = () => {
  getUserList(queryParams.value).then((res) => {
    userList.value = res.data.records;
    total.value = res.data.total;
  });
};

const handleQuery = () => {
  queryParams.value.current = 1;
  getList();
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="less">
.order-warp {
  .operate {
    margin-bottom: 20px;
  }

  .footer {
    padding: 10px 0;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
